package org.deyang.tools.amazon;

import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.deyang.tools.amazon.exceptions.KeepaContentException;
import org.deyang.tools.amazon.pricetracker.KeepaPriceAnalyzer;
import org.deyang.tools.amazon.utils.AmazonXMLProcessor;
import org.deyang.tools.amazon.utils.GlobalConstants;
import org.deyang.tools.amazon.utils.SignedRequestsHelper;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Text;

public class AddTrackListServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2415386563258688627L;
	private static final Logger log = Logger.getLogger(AddTrackListServlet.class.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		String asin = req.getParameter("asin");
		
		/*
         * Set up the signed requests helper 
         */
        SignedRequestsHelper helper = null;
        try {
            helper = SignedRequestsHelper.getInstance(GlobalConstants.ENDPOINT, GlobalConstants.AWS_ACCESS_KEY_ID, GlobalConstants.AWS_SECRET_KEY);
        } catch (Exception e) {
            e.printStackTrace();
            resp.setStatus(403);
        }
        Map<String, String> params = new HashMap<String, String>();
        params.put("Service", GlobalConstants.SERVICE_NAME);
        params.put("AssociateTag", GlobalConstants.ASSOCIATE_TAG);
        params.put("Operation", "SimilarityLookup");
        params.put("ItemId", asin);
        params.put("Condition", "New");
        params.put("SimilarityType", "Random");
        params.put("ResponseGroup", "Medium");
        
        String requestUrl = helper.sign(params);
		
        try {
			URL url = new URL(requestUrl);
			
			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        	DocumentBuilder db = dbf.newDocumentBuilder();
        	Document domDoc = db.parse(url.openStream());
        	NodeList itemList = domDoc.getElementsByTagName("Item");
        	
        	DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        	for (int i = 0; i < itemList.getLength(); i++){
        		Query productQ = new Query("AmazonProduct");
        		Element itemElement = (Element) itemList.item(i);
        		String similiarasin = AmazonXMLProcessor.getDefaultChildNodeValue((Element) itemElement, "ASIN");
        		productQ.addFilter("asin", Query.FilterOperator.EQUAL, similiarasin);
        		PreparedQuery pq = datastore.prepare(productQ);
        		Iterator<Entity> iter = pq.asIterator();
        		if (!iter.hasNext()){
        			//In case this product is not recorded in db,add it into db
        			Entity resultEntity = new Entity("AmazonProduct");
        			Element mediumImageElement = AmazonXMLProcessor.getDefaultChildNode(itemElement, "MediumImage");
        			Element arrtElement = AmazonXMLProcessor.getDefaultChildNode(itemElement, "ItemAttributes");
        			
        			resultEntity.setProperty("asin", similiarasin);
        			try {
    					KeepaPriceAnalyzer kpa = new KeepaPriceAnalyzer(similiarasin);
    					resultEntity.setProperty("PriceHistoryData",new Text(kpa.getAmazonPriceHistoryStr()));
    				} catch (KeepaContentException e) {
    					log.warning(e.getMessage());
    					e.printStackTrace();
    				}
        			resultEntity.setProperty("imgurl",AmazonXMLProcessor.getDefaultChildNodeValue(mediumImageElement, "URL"));
        			resultEntity.setProperty("amazonProductTitle", AmazonXMLProcessor.getDefaultChildNodeValue(arrtElement, "Title"));
        			resultEntity.setProperty("trackStatus", "T");
        			String urlStr = AmazonXMLProcessor.getDefaultChildNodeValue(itemElement, "DetailPageURL");
        			if (urlStr.length() >= 500){
        				resultEntity.setProperty("shorturl", new Text(urlStr));
        			}else{
        				resultEntity.setProperty("shorturl", urlStr);	
        			}
        			datastore.put(resultEntity);
        		}
        	}
        	resp.setStatus(200);
        } catch (ParserConfigurationException e) {
			e.printStackTrace();
			log.severe(e.getMessage());
			resp.setStatus(401);
		} catch (SAXException e) {
			e.printStackTrace();
			log.severe(e.getMessage());
			resp.setStatus(403);
		}
	}
}
